export interface CustomIconOptions {
  scriptUrl?: string | string[]
}

const customCache = new Set<string>()

function isValidCustomScriptUrl(scriptUrl: string): boolean {
  return Boolean(typeof scriptUrl === 'string' && scriptUrl.length && !customCache.has(scriptUrl))
}

export default function createFromIconfontCN(scriptUrls: string[], index = 0): void {
  if (!Array.isArray(scriptUrls)) throw new Error('scriptUrl接收的是字符串数组类型')
  const currentScriptUrl = scriptUrls[index]
  if (isValidCustomScriptUrl(currentScriptUrl)) {
    const script = document.createElement('script')
    script.setAttribute('src', currentScriptUrl)
    script.setAttribute('data-namespace', currentScriptUrl)
    if (scriptUrls.length > index + 1) {
      script.onload = () => {
        createFromIconfontCN(scriptUrls, index + 1)
      }
      script.onerror = () => {
        createFromIconfontCN(scriptUrls, index + 1)
      }
    }
    customCache.add(currentScriptUrl)
    document.body.appendChild(script)
  }
}
